package com.ehotting.edsta.circuitDesign.gen.element.bean;

import com.ehotting.edsta.circuitDesign.domain.EsElement;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class EsArrayList<E> extends ArrayList<E> {

    @Override
    public boolean add(E e){
        if(!this.contains(e)){
            return super.add(e);
        }
        return false;
    }

    @Override
    public boolean addAll(Collection<? extends E> c){
        Object[] aa = c.toArray();
        List list = new EsArrayList<>();
        for(Object a: aa){
            if(!this.contains(a)){
                list.add(a);
            }
        }
        return super.addAll(list);
    }

    @Override
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    @Override
    public int indexOf(Object b) {
        for( Object a : this){
            if(areEqual(a, b))
                return 1;
        }
        return -1;
    }

    private boolean areEqual(Object first1, Object second1) {
        Map<String, EsElement> first = (Map<String, EsElement>)first1;
        Map<String, EsElement> second = (Map<String, EsElement>)second1;
        int firstLen = first.entrySet().stream().filter(e->{return e.getValue() instanceof EsElement;}).toArray().length;
        int secondLen = second.entrySet().stream().filter(e->{return e.getValue() instanceof EsElement;}).toArray().length;
        if (firstLen != secondLen) {
            return false;
        }
        return first.entrySet().stream().filter(e->{return e.getValue()!=null && e.getValue() instanceof EsElement;}).allMatch(
                e -> e.getValue()!=null
                        && second.get(e.getKey())!=null
                        && e.getValue().getId().equals(second.get(e.getKey()).getId()));
    }

}
